package com.qr.activitys;

import android.Manifest;
import android.content.pm.PackageManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import com.qr.activitys.http.manager.HomeManager;
import com.tbruyelle.rxpermissions2.Permission;
import com.tbruyelle.rxpermissions2.RxPermissions;

import org.zackratos.ultimatebar.UltimateBar;

import cn.bingoogolapple.qrcode.core.QRCodeView;
import cn.bingoogolapple.qrcode.zbar.ZBarView;
import io.reactivex.functions.Consumer;

public class MainActivity extends AppCompatActivity implements QRCodeView.Delegate, View.OnClickListener {

    //二维码扫描控件
    private ZBarView mZBarView;
    //返回按钮
    private ImageView mIvDestroy;
    //设置按钮
    private ImageView mIvFunction;
    //闪光灯按钮
    private ImageView mIvLamp;

    //闪光灯标记
    private boolean mFlashLampFlag = true;
    //播放音频
    private MediaPlayer mMediaPlayer;

    //需要延时几秒
    private int second = 5000;

    //初始化网络请求
    public HomeManager mApiManager;
    //缓存管理
    private ACache mACache;
    //存储秒数 key
    public static final String CACHE_SECOND_KEY = "cache_second_key";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //TODO 实例化参数配置
        mACache = ACache.get(this);
        //网络请求接口 常驻方法
        mApiManager = mApiManager.getHomeApiManager(this,this.getTaskId());

        //直接创建 MediaPlayer 对象
        mMediaPlayer = MediaPlayer.create(this, R.raw.qr_code_music);

        //初始化 扫描控件
        mZBarView = findViewById(R.id.view_z_bar);
        mIvDestroy = findViewById(R.id.iv_destroy);
        mIvFunction = findViewById(R.id.iv_function);
        mIvLamp = findViewById(R.id.iv_lamp);

        //注册
        mZBarView.setDelegate(this);

        //TODO 按钮点击事件
        //返回
        mIvDestroy.setOnClickListener(this);
        //设置
        mIvFunction.setOnClickListener(this);
        //闪关灯
        mIvLamp.setOnClickListener(this);

        //获取保存的 数据
        String key = mACache.getAsString(CACHE_SECOND_KEY);
        if (key!=null && !"".equals(key)){
            second = Integer.parseInt(key);
        }

        //TODO 配置相应的权限
        requestPermissions();
        //设置透明的标题栏与状态栏
        UltimateBar ultimateBar = new UltimateBar(this);
        ultimateBar.setImmersionBar();
    }

    //开始
    @Override
    protected void onStart() {
        super.onStart();
        startScanning();
    }
    //结束
    @Override
    protected void onStop() {
        stopScanning();
        super.onStop();
    }
    //销毁
    @Override
    protected void onDestroy() {
        //释放资源
        mMediaPlayer.release();
        destroyScanning();
        super.onDestroy();
    }

    /**
     * 开始扫描
     */
    private void startScanning(){
        // 打开后置摄像头开始预览，但是并未开始识别
        mZBarView.startCamera();
        // 显示扫描框，并且延迟0.5秒后开始识别
        mZBarView.startSpotAndShowRect();
    }

    /**
     * 停止扫描
     */
    private void stopScanning(){
        //关闭摄像头预览，并且隐藏扫描框
        mZBarView.stopCamera();
    }

    /**
     * 销毁扫描
     */
    private void destroyScanning(){
        // 销毁二维码扫描控件
        mZBarView.onDestroy();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.iv_destroy:
                finish();
                break;
            case R.id.iv_function:
                new InputDialog.Builder(this)
                        .setTitle("设置延时毫秒")
                        .setInputDefaultText(second+"")
                        .setInputHint("单位/毫秒")
                        .setPositiveButton("确定", new InputDialog.ButtonActionListener() {
                            @Override
                            public void onClick(CharSequence inputText) {
                                //初始延时秒数
                                if (!"".equals(inputText.toString()))
                                    second = Integer.parseInt(inputText.toString());
                                // TODO 将数据保存到本地
                                mACache.put(CACHE_SECOND_KEY,second+"");
                            }
                        })
                        .setOnCancelListener(new InputDialog.OnCancelListener() {
                            @Override
                            public void onCancel(CharSequence inputText) {

                            }
                        })
                        .show();
                break;
            case R.id.iv_lamp:
                if(!getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH)) {
                    Toast.makeText(this, "没有找到闪光灯设备", Toast.LENGTH_LONG).show();
                }else{
                    if (mFlashLampFlag){
                        mZBarView.openFlashlight(); // 打开闪光灯
                        mIvLamp.setImageResource(R.drawable.flash_lamp_open);
                        mFlashLampFlag = false;
                    }else{
                        mZBarView.closeFlashlight(); // 关闭闪光灯
                        mIvLamp.setImageResource(R.drawable.flash_lamp_shut);
                        mFlashLampFlag = true;
                    }
                }
                break;
        }
    }


    /**
     * 权限申请
     * 相机：  CAMERA
     * 闪光灯：READ_EXTERNAL_STORAGE
     */
    private void requestPermissions() {
        RxPermissions rxPermission = new RxPermissions(MainActivity.this);

        rxPermission.requestEach(
                Manifest.permission.CAMERA,
                Manifest.permission.READ_EXTERNAL_STORAGE)
                .subscribe(new Consumer<Permission>() {
                    @Override
                    public void accept(Permission permission) throws Exception {
                        if (permission.granted) {
                            //初始化扫描
                            startScanning();
                            // 用户已经同意该权限
                            Log.d("Permission：",permission.name + " is granted.");
                        } else if (permission.shouldShowRequestPermissionRationale) {
                            // 用户拒绝了该权限，没有选中『不再询问』（Never ask again）,那么下次再次启动时，还会提示请求权限的对话框
                            Log.d("Permission：",permission.name + " is denied. More info should be provided.");
                        } else {
                            // 用户拒绝了该权限，并且选中『不再询问』
                            Log.d("Permission：",permission.name + " is denied. More info should be provided.");
                        }
                    }
                });
    }

    @Override
    public void onScanQRCodeSuccess(String result) {
        //播放音乐
        mMediaPlayer.start();
        //输出log
        Log.i("result:---------->", result);
        //下一次扫描延迟 3s
        mZBarView.startSpotDelay(second);
        //输出log
        Toast.makeText(MainActivity.this,"second:---------->"+second+"ms\nresult:---------->"+result,Toast.LENGTH_SHORT).show();
        //开始网络请求 将解析数据 传递到服务器上
        mApiManager.httpPostData(result);

    }

    @Override
    public void onScanQRCodeOpenCameraError() {
        Log.i("result:---------->", "打开相机出错");
    }

    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {

    }
}
